/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller.xml;

import Common.Utils;
import Model.AccountModel;
import Model.Dto.Account;
import Model.Dto.jaxb.AccountBalances.AccountBalances;
import Model.Dto.jaxb.Transasctions.TransactionType;
import Model.Dto.jaxb.Transasctions.Transactions;
import Model.TransactionModel;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Quang Nhat
 */
public class AccountantXML extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            String action = request.getParameter("action");
            if ("listAccount".equalsIgnoreCase(action)) {
                out.write(Utils.MarshallXML(AccountModel.getJAXBAccounts(), true));
            } else if ("xslAccountCombo".equalsIgnoreCase(action)) {
                String path = getServletContext().getRealPath("/WEB-INF/xml/AccountCombo.xsl");
                BufferedReader in = null;
                try {
                    in = new BufferedReader( new InputStreamReader(new BufferedInputStream(new FileInputStream(path))));

                    String line;
                    while ((line = in.readLine()) != null) {
                        out.println(line);
                    }
                } finally {
                    if (in != null) {
                        in.close();
                    }
                }
            } else if ("addAccount".equalsIgnoreCase(action)) {
                String message = "";
                String sAccNumber = request.getParameter("accNumber");
                String accName = request.getParameter("accName");
                boolean active = request.getParameter("active") != null;
                int accNumber = 0;
                try {
                    accNumber = Integer.parseInt(sAccNumber);
                    if (accNumber < 100) {
                        message += "Invalid Account number.";
                    }
                } catch (NumberFormatException ex) {
                    message += "Invalid Account number.";
                }
                if (accName == null || accName.trim().length() == 0) {
                    message += "Account name cannot be null or emtpy.";
                }
                if (message.length() == 0) {
                    if (!AccountModel.addAccount(new Account(accNumber, accName, active))) {
                        message += "Account number is already exists.";
                    }
                }
                out.write(message);
            } else if ("updateAccount".equalsIgnoreCase(action)) {
                String message = "";
                String sAccNumber = request.getParameter("accNumber");
                String accName = request.getParameter("accName");
                boolean active = request.getParameter("active") != null;
                int accNumber = 0;
                try {
                    accNumber = Integer.parseInt(sAccNumber);
                    if (accNumber < 100) {
                        message += "Invalid Account number.";
                    }
                } catch (NumberFormatException ex) {
                    message += "Invalid Account number.";
                }
                if (accName == null || accName.trim().length() == 0) {
                    message += "Account name cannot be null or emtpy.";
                }
                if (message.length() == 0) {
                    if (!AccountModel.updateAccount(new Account(accNumber, accName, active))) {
                        message += "Account number is already exists.";
                    }
                }
                out.write(message);
            } else if ("addTransaction".equalsIgnoreCase(action)) {
                String content = request.getParameter("content");
                if (content != null) {
                    content = new String(content.getBytes("8859_1"), "UTF8");
                }
                Transactions res = TransactionModel.parseXML(content);
                for (TransactionType tran : res.getTransaction()) {
                    int id = TransactionModel.addTransaction(tran);
                    out.println(id);
                }
            } else if ("deleteTransaction".equalsIgnoreCase(action)) {
                String txtId = request.getParameter("Id");
                try {
                    int id = Integer.parseInt(txtId);
                    TransactionModel.deleteTransaction(id);
                } catch (Exception ex) {
                    Utils.ReportException(ex);
                    out.write(ex.getMessage());
                }
            } else if ("getTransaction".equalsIgnoreCase(action)) {
                String txtId = request.getParameter("Id");
                try {
                    int id = Integer.parseInt(txtId);
                    Transactions res = new Transactions();
                    res.getTransaction().add(TransactionModel.getTransactionById(id));
                    out.write(Utils.MarshallXML(res, true));
                } catch (Exception ex) {
                    Utils.ReportException(ex);
                    out.write(ex.getMessage());
                }
            } else if ("searchTransaction".equalsIgnoreCase(action)) {
                String text = request.getParameter("text");
                String message = "";
                if (text != null) {
                    text = new String(text.getBytes("8859_1"), "UTF8");
                } else {
                    text = "";
                }
                Date minDate = null;
                Date maxDate = null;
                String txtMinDate = request.getParameter("txtMinDate");
                if (txtMinDate != null && txtMinDate.length() > 0) {
                    minDate = Utils.parseDate(txtMinDate);
                    if (minDate == null) {
                        message += "Invalid From Date.";
                    }
                } else {
                    txtMinDate = "";
                }
                String txtMaxDate = request.getParameter("txtMaxDate");
                if (txtMaxDate != null && txtMaxDate.length() > 0) {
                    maxDate = Utils.parseDate(txtMaxDate);
                    if (maxDate == null) {
                        message += "Invalid To Date.";
                    }
                } else {
                    txtMaxDate = "";
                }
                Transactions res = TransactionModel.searchTransaction(minDate, maxDate, text);
                out.write(Utils.MarshallXML(res, true));
            } else if ("updateTransaction".equalsIgnoreCase(action)) {
                String content = request.getParameter("content");
                if (content != null) {
                    content = new String(content.getBytes("8859_1"), "UTF8");
                }
                Transactions res = TransactionModel.parseXML(content);
                for (TransactionType tran : res.getTransaction()) {
                    boolean id = TransactionModel.updateTransaction(tran);
                    out.println(id);
                }
            } else if ("accountBalances".equalsIgnoreCase(action)) {
                String txtDate = request.getParameter("txtDate");
                Date date = null;
                if (txtDate != null) {
                    date = Utils.parseDate(txtDate);
                }
                if (date == null) {
                    java.util.Date currDate = new java.util.Date();
                    date = new Date(currDate.getYear(), currDate.getMonth(), currDate.getDate());
                }
                AccountBalances res = TransactionModel.getJaxbAccountBalances(date);
                out.write(Utils.MarshallXML(res, true));
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
